package com.lx.yygh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lx.yygh.cmn.client.DictFeignClient;
import com.lx.yygh.common.exception.YyghException;
import com.lx.yygh.common.helper.JwtHelper;
import com.lx.yygh.common.result.ResultCodeEnum;
import com.lx.yygh.common.util.IpUtil;
import com.lx.yygh.enums.AuthStatusEnum;
import com.lx.yygh.mapper.UserInfoMapper;
import com.lx.yygh.mapper.UserLoginRecordMapper;
import com.lx.yygh.model.user.UserInfo;
import com.lx.yygh.model.user.UserLoginRecord;
import com.lx.yygh.service.UserInfoService;
import com.lx.yygh.vo.user.LoginVo;
import com.lx.yygh.vo.user.UserAuthVo;
import com.lx.yygh.vo.user.UserInfoQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author c先生
 * @date 2022年10月20日 下午 12:23:25
 * @describe
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Resource
    UserInfoMapper userInfoMapper;
    @Resource
    UserLoginRecordMapper userLoginRecordMapper;
    @Resource
    RedisTemplate redisTemplate;
    @Autowired
    DictFeignClient dictFeignClient;


    @Override
    public Map<String,Object> loginCheck(LoginVo loginVo, HttpServletRequest request) {
        Map<String,Object> map = new HashMap<>();
        //获取登录信息
        String phone = loginVo.getPhone();//用户登录的手机号
        String code = loginVo.getCode();//用户输入的验证码
        String openid = loginVo.getOpenid();
        //判断验证码是否为空
        if(!StringUtils.hasText(loginVo.getCode())){
            //验证码为空
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        //根据手机号从redis中获取验证码
        String code4Redis = (String) redisTemplate.opsForValue().get(phone);
        //验证验证码是否正确
        if(!code.equals(code4Redis)){
            throw new YyghException(ResultCodeEnum.CODE_ERROR);
        }

        //首先查询数据里是否存在该手机号，如果不存在进行注册，如果存在，则进行登录验证
        QueryWrapper query = new QueryWrapper();
        query.eq("phone",loginVo.getPhone());
        UserInfo user = userInfoMapper.selectOne(query);

        if(StringUtils.hasText(openid)){
            //如果是微信登录过来的，那么就绑定手机号
            QueryWrapper query2 = new QueryWrapper();
            query2.eq("openid",openid);
            UserInfo user2 = userInfoMapper.selectOne(query2);
            if(null!=user2){
                user2.setPhone(phone);
                this.updateById(user2);
            }
        }else{
            if(user==null){
                //注册
                UserInfo userInfo = new UserInfo();
                BeanUtils.copyProperties(loginVo,userInfo);
                //将数据插入数据库中
                userInfoMapper.insert(userInfo);
                //生成token
                String token = JwtHelper.createToken(userInfo.getId(), userInfo.getPhone());
                map.put("name",userInfo.getPhone());
                map.put("token",token);
                //注册成功
                return map;
            }else {
                //登录验证
                //判断账号是否被禁用
                Integer status = user.getStatus();
                if(status==1){
                    //账号未锁定,存储登录记录
                    UserLoginRecord userLoginRecord = new UserLoginRecord();
                    //获取用户登录ip
                    String ipAddr = IpUtil.getIpAddr(request);
                    userLoginRecord.setUserId(user.getId());
                    userLoginRecord.setIp(ipAddr);
                    //保存登录记录到数据库中
                    userLoginRecordMapper.insert(userLoginRecord);
                }
            }
        }


        //有名字就展示名字，没有名字就展示昵称，没有昵称就展示手机号
        String name = "";
        if(StringUtils.hasText(user.getPhone())){
            name = user.getPhone();
        }
        if(StringUtils.hasText(user.getNickName())){
            name = user.getNickName();
        }
        if(StringUtils.hasText(user.getName())){
            name = user.getName();
        }

        //生成token
        map.put("name",name);
        String token = JwtHelper.createToken(user.getId(), name);
        map.put("token",token);
        //登录成功
        return map;
    }

    @Override
    public UserInfo getUserInfo(Long userId) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("id",userId);
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        return userInfo;
    }

    @Override
    public Boolean saveUserAuah(UserAuthVo userAuthVo,Long userId) {

        UserInfo userInfo = baseMapper.selectById(userId);
        //设置认证信息
        //认证人姓名
        userInfo.setName(userAuthVo.getName());
        //其他认证信息
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        //进行信息更新
        int i = baseMapper.updateById(userInfo);
        if(i==1){
            return true;
        }
        return false;
    }

    @Override
    public IPage<UserInfo> getPageList(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        if(userInfoQueryVo==null){
            userInfoQueryVo = new UserInfoQueryVo();
        }
        //用户状态
        Integer status = userInfoQueryVo.getStatus();
        //认证状态
        Integer authStatus = userInfoQueryVo.getAuthStatus();
        //手机号或者用户名
        String keyword = userInfoQueryVo.getKeyword();
        //开始时间
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
        //结束时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if(StringUtils.hasText(createTimeBegin)){
            wrapper.ge("create_time",createTimeBegin);
        }
        if(StringUtils.hasText(createTimeEnd)){
            wrapper.le("create_time",createTimeEnd);
        }
        if(!StringUtils.isEmpty(status)){
            wrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(authStatus)){
            wrapper.eq("auth_status",authStatus);
        }
        if(StringUtils.hasText(keyword)){
            wrapper.and(queryWapper->queryWapper.like("name",keyword).or().like("phone",keyword));
//            wrapper.like("name",keyword).or().like("phone",keyword);
        }

        IPage<UserInfo> pages = baseMapper.selectPage(pageParam, wrapper);
        List<UserInfo> records = pages.getRecords();
        for (UserInfo record : records) {
            this.packageUserInfo(record);
        }
        return pages;
    }

    private void packageUserInfo(UserInfo record) {
        Integer status = record.getStatus();
        String statusString = status.intValue()==0?"锁定":"正常";
        Integer authStatus = record.getAuthStatus();
        String authStatusString = AuthStatusEnum.getStatusNameByStatus(authStatus);
        String certificatesType = record.getCertificatesType();
        String certificatesTypeString = dictFeignClient.getName(certificatesType);
        HashMap<String, Object> map = new HashMap<>();
        map.put("statusString",statusString);
        map.put("authStatusString",authStatusString);
        map.put("certificatesTypeString",certificatesTypeString);
        record.setParam(map);
    }

    @Override
    public Boolean lock(Long id, Integer status) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setStatus(status);
        int i = baseMapper.updateById(userInfo);
        if(i>0){
            return true;
        }
        return false;
    }

    @Override
    public UserInfo findUserInfoById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public Boolean updateAuthstatusById(Long id, Integer authStatus) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setAuthStatus(authStatus);
        return baseMapper.updateById(userInfo)>0?true:false;
    }
}




















